package cn.byzk.xframe.web.session.annotations;

import cn.byzk.xframe.web.session.util.SessionUtil;
import cn.byzk.xframe.web.session.TokenMemory;
import cn.byzk.xframe.web.session.model.SessionUser;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class ToLoginTokenAspect {

    @Autowired
    private TokenMemory tokenMemory;

    /**
     * 定义切入点
     * @author xcf
     * @date 2021/5/6 9:20
     * @param toLoginToken
     */
    @Pointcut(value = "@annotation(toLoginToken)", argNames = "toLoginToken")
    public void pointcut(ToLoginToken toLoginToken) {

    }




    /**
     * return前进行处理,Token
     * @author xcf
     * @date 2021/5/6 10:10
     * @param joinPoint
     * @param userObj
     */
    @AfterReturning(value = "@annotation(cn.byzk.xframe.web.session.annotations.ToLoginToken)", returning = "userObj")
    public void afterReturning(JoinPoint joinPoint, Object userObj) {

        SessionUser sessionUser = (SessionUser) userObj;


        String token = tokenMemory.create(sessionUser);
        log.warn("用户ID:{},生成的Token:{}", sessionUser.getUserId(), token);

        if (1 == sessionUser.getPos()) {
            SessionUtil.setToken(SessionUser.TOKEN_KEY,token);
        } else if (2 == sessionUser.getPos()) {
            SessionUtil.setToken(SessionUser.TOKEN_KEY_2,token);
        } else if (3 == sessionUser.getPos()) {
            SessionUtil.setToken(SessionUser.TOKEN_KEY_3,token);
        }


    }
}
